//prueba cambio git
package com.javier.nfcpass;

import android.R.string;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

public class GestorBD {


	private static final String TABLE_PASS = "Sitios";

	private static final class TSitios implements BaseColumns {
		
		private TSitios() {}

		public static final String ID_COLUMN = "_id";
		public static final String PASS_COLUMN = "Pass";
		public static final String USER_COLUMN = "User";
		public static final String NOMBRE_COLUMN = "Nombre";
		public static final String URL_COLUMN = "Url";
		public static final String ID_TAG = "idTag";
	}

	// Database open/upgrade helper
	private DBHandle openHelper;

	public GestorBD(Context context) {
		openHelper = new DBHandle(context, DBHandle.DATABASE_NAME, null, DBHandle.DATABASE_VERSION);
	}

	// Called when you no longer need access to the database.
	public void closeDatabase() {
		openHelper.close();
	}

	public Cursor obtenerTodosSitios(String idTag) {
		// Specify the result column projection.
		String[] result_columns = new String[] { TSitios.ID_COLUMN, TSitios.NOMBRE_COLUMN };

		// Specify the where clause that will limit our results.
		String where =  TSitios.ID_TAG + "= ?" ;

		// Replace these with valid SQL statements as necessary.
		String whereArgs[] = {idTag};
		String groupBy = null;
		String having = null;
		String order = null;

		SQLiteDatabase db = openHelper.getWritableDatabase();
		Cursor cursor = db.query(DBHandle.DATABASE_TABLE, result_columns, where, whereArgs, groupBy, having, order);

		return cursor;
	}

	public Cursor obtenerSitioPorID(int idSitio) {
		// Specify the result column projection.
		String[] result_columns = new String[] {TSitios.USER_COLUMN, TSitios.PASS_COLUMN};

		// Specify the where clause that will limit our results.
		String where =  TSitios.ID_COLUMN + "= ?";

		// Replace these with valid SQL statements as necessary.
		String whereArgs[] = {String.valueOf(idSitio)};
		String groupBy = null;
		String having = null;
		String order = null;

		SQLiteDatabase db = openHelper.getWritableDatabase();
		Cursor cursor = db.query(DBHandle.DATABASE_TABLE, result_columns, where, whereArgs, groupBy, having, order);

	 
		return cursor;
	}
	
	public float getAverageAccessibleHoardValue() {
		Cursor cursor = obtenerTodosSitios("");

		/**
		 * Listing 8-4: Extracting values from a Cursor
		 */
		float totalHoard = 0f;
		float averageHoard = 0f;

		// Find the index to the column(s) being used.
		int GOLD_HOARDED_COLUMN_INDEX = cursor.getColumnIndexOrThrow(TSitios.NOMBRE_COLUMN);

		// Iterate over the cursors rows.
		// The Cursor is initialized at before first, so we can
		// check only if there is a "next" row available. If the
		// result Cursor is empty this will return false.
		while (cursor.moveToNext()) {
			float hoard = cursor.getFloat(GOLD_HOARDED_COLUMN_INDEX);
			totalHoard += hoard;
		}

		// Calculate an average -- checking for divide by zero errors.
		float cursorCount = cursor.getCount();
		averageHoard = cursorCount > 0 ? (totalHoard / cursorCount) : Float.NaN;

		// Close the Cursor when you've finished with it.
		cursor.close();

		return averageHoard;
	}

	public void crearSitio(String nombre, String usuario, String pass, String url, String idTag) {

		// Create a new row of values to insert.
		ContentValues newValues = new ContentValues();

		// Assign values for each row.	
		newValues.put(TSitios.NOMBRE_COLUMN, nombre);
		newValues.put(TSitios.USER_COLUMN, usuario);
		newValues.put(TSitios.PASS_COLUMN, pass);
		newValues.put(TSitios.URL_COLUMN, url);
		newValues.put(TSitios.ID_TAG, idTag);
		
		// Insert the row into your table
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.insert(DBHandle.DATABASE_TABLE, null, newValues);
		db.close();
	}

	public void actualizarPass(int idSitio, String nuevoPassword) {

		// Create the updated row Content Values.
		ContentValues updatedValues = new ContentValues();

		// Assign values for each row.
		updatedValues.put(TSitios.PASS_COLUMN, nuevoPassword);

		String where = TSitios.ID_COLUMN + "=" + idSitio;
		String whereArgs[] = null;
		SQLiteDatabase db = openHelper.getWritableDatabase();
		
		db.update(DBHandle.DATABASE_TABLE, updatedValues, where, whereArgs);
	}

	public void borrarSitio(int idSitio) {

		String where = TSitios.ID_COLUMN + "= ?";
		String whereArgs[] = {String.valueOf(idSitio)};

		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.delete(DBHandle.DATABASE_TABLE, where, whereArgs);
	}

	// Implementing an SQLite Open Helper
	private static class DBHandle extends SQLiteOpenHelper {

		private static final String DATABASE_NAME = "NFCPass.db";
		private static final String DATABASE_TABLE = "Sitios";
		private static final int DATABASE_VERSION = 2;

		// SQL Statement to create a new database.
		private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + " (" + 
								TSitios.ID_COLUMN + " integer primary key autoincrement, " + 
								TSitios.NOMBRE_COLUMN + " text not null, " + 
								TSitios.USER_COLUMN + " text not null, " + 
								TSitios.PASS_COLUMN + " text not null, " + 
								TSitios.URL_COLUMN + " text not null," + 
								TSitios.ID_TAG + " text not null);";

		public DBHandle(Context context, String name, CursorFactory factory, int version) {
			super(context, name, factory, version);
		}

		// Called when no database exists in disk and the helper class needs to
		// create a new one.
		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
		}

		// Called when there is a database version mismatch meaning that
		// the version of the database on disk needs to be upgraded to
		// the current version.
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// Log the version upgrade.
			Log.w("TaskDBAdapter", "Upgrading from version " + oldVersion + " to " + newVersion
					+ ", which will destroy all old data");

			// Upgrade the existing database to conform to the new
			// version. Multiple previous versions can be handled by
			// comparing oldVersion and newVersion values.

			// The simplest case is to drop the old table and create a new one.
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			// Create a new one.
			onCreate(db);
		}
	}
}